<!-- 新建子站点模态框 -->
<template>
  <a-form name="advanced_search" class="ant-advanced-search-form" :model="formState" ref="createSiteFrom"
    autoComplete="off">
    <a-form-item :label="formState.parent.label" v-if="!Object.keys(props.baseFromInfo).length">
      <span>{{ formState.parent.value }}</span>
    </a-form-item>
    <a-form-item :name="['siteName', 'value']" :label="formState.siteName.label" :rules="[formState.siteName.rule]">
      <a-input v-model:value="formState.siteName.value" @blur="valueChange(formState.siteName.rule.key, {})"
        :placeholder="formState.siteName.placeholder" show-count :maxlength="100" allow-clear @input="changeSiteName" />
    </a-form-item>
    <a-form-item :name="['sitePath', 'value']" :label="formState.sitePath.label" class="sitePath"
      :rules="[formState.sitePath.rule]">
      <a-input v-model:value="formState.sitePath.value" :placeholder="formState.sitePath.placeholder"
        :allow-clear="formState.description.value" show-count :maxlength="100"
        @blur="valueChange(formState.sitePath.rule.key, {})" ref="sitePath_ref" />
    </a-form-item>
    <a-form-item :name="['siteDomain', 'value']" :label="formState.siteDomain.label" :rules="[formState.siteDomain.rule]"
      class="siteDomain">
      <a-input-group compact>
        <a-form-item-rest>
          <a-select v-model:value="formState.siteProtocol.value" style="width:107px" @change="selectChange">
            <template v-for="item in formState.siteProtocol.options">
              <a-select-option :value="item">{{ item }}</a-select-option>
            </template>
          </a-select>
        </a-form-item-rest>
        <a-input class="siteDomain-input" v-model:value="formState.siteDomain.value" show-count :maxlength="200"
          :allow-clear="formState.siteDomain.value" @blur="valueChange(formState.siteDomain.rule.key, {})" ref="ipt" />
      </a-input-group>
    </a-form-item>
    <template v-for="(item, index) in formState.siteDomainAlias" :key="index">
      <a-form-item class="otherFormItems" :name="['siteDomainAlias', index, 'value']" :rules="[item.rule]">
        <a-input-group compact class="otherSiteProtocols">
          <a-form-item-rest>
            <a-select v-model:value="formState.siteProtocol.value" :disabled="true" style="width:107px">
              <template v-for="data in   formState.siteProtocol.options">
                <a-select-option :value="data">{{ data }}</a-select-option>
              </template>
            </a-select>
          </a-form-item-rest>
          <a-input v-model:value="item.value" show-count :maxlength="200" :allow-clear="item.value" @focus=""
            class="siteDomainAlias-input" @blur="valueChange('', item)" />
          <span class="iconfont delete-iconfont" @click="deleteOtherSPList(index)">&#xe8e2;</span>
        </a-input-group>
      </a-form-item>
    </template>

    <div class="addSiteDomain" :class="otherSiteProtocolsList.length ? 'addSiteDomain_maringTop' : ''"><span
        @click="addSiteDomain">新增域名</span></div>
    <a-form-item :label="formState.description.label" class="description">
      <a-textarea v-model:value="formState.description.value" show-count :maxlength="500"
        :allow-clear="formState.description.value" :placeholder="formState.description.placeholder" />
    </a-form-item>
    <a-form-item :label="formState.status.label" class="status">
      <a-popconfirm placement="topLeft" ok-text="关闭" cancel-text="取消" @confirm="closeSite"
        v-if="Object.keys(props.baseFromInfo).length && formState.status.value == true">
        <template #title>
          <p style="width: 197px">
            关闭站点后，前台用户将无法浏览站点内容，站点管理后台依旧可以操作
          </p>
        </template>
        <a-switch size="small" v-model:checked="formState.status.value"
          @change="formState.status.value = true"></a-switch>
      </a-popconfirm>

      <a-switch size="small" v-model:checked="formState.status.value" v-else></a-switch>
      <span class="setTime" v-if="Object.keys(props.baseFromInfo).length && formState.status.value"
        @click="checkSetTime">查看站点定时开关任务</span>
    </a-form-item>
    <a-form-item :name="['channelCopyOptions', 'value']" :label="formState.channelCopyOptions.label"
      :rules="[formState.channelCopyOptions.rule]" class="channelCopyOptions">
      <a-radio-group v-model:value="formState.channelCopyOptions.value"
        :disabled="Object.keys(props.baseFromInfo).length">
        <a-radio :value="0">不复制父级栏目</a-radio>
        <a-radio :value="1">复制父级站点栏目</a-radio>
        <a-radio :value="2">复制父级站点栏目及栏目配置</a-radio>
      </a-radio-group>
    </a-form-item>
    <div class="SEOSetting">SEO搜索设置</div>
    <a-form-item :label="formState.seoTitle.label">
      <a-input v-model:value="formState.seoTitle.value" :placeholder="formState.seoTitle.placeholder" show-count
        :maxlength="25" allow-clear />
    </a-form-item>
    <a-form-item :label="formState.seoKeyword.label">
      <a-input v-model:value="formState.seoKeyword.value" :placeholder="formState.seoKeyword.placeholder" show-count
        :maxlength="25" allow-clear />
    </a-form-item>
    <a-form-item :label="formState.seoDescription.label">
      <a-textarea v-model:value="formState.seoDescription.value" show-count :maxlength="500"
        :placeholder="formState.seoDescription.placeholder" />
    </a-form-item>
  </a-form>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch, nextTick } from "vue"
import msgModal from "@/components/modal/modelConfig/MsGModal";
import request from "@/api/index";
import { checkCreatSiteForm, detectKey, enNum } from "./formRuler"
import { cloneDeep } from 'lodash'
import { Data } from "ant-design-vue/es/_util/type";
const checkSiteDomainAlias = async (_rule: dataSourceType = {}, value: any) => {
  if (_rule.required) {// 必填项验证非空并排除非必须项
    if (!value && value !== 0) {
      return Promise.reject(`${_rule.msg1}`);
    }
  }
  if (value || value === 0) {// 没变化没校验的必要
    if (value == formState.siteDomain.value && _rule.key == 'siteDomainAlias') {
      return Promise.reject('列表或回收站中已存在相同的站点名称，请重新输入！');
    } else {
      let arr: any = [];
      formState.siteDomainAlias.map((item: dataSourceType) => {
        if (item.value == value) {
          arr.push(item.value)
        }
      })
      if (arr.length > 1 || (arr.length && _rule.key == 'siteDomain')) {
        return Promise.reject(`${_rule.msg2}`);
      } else {
        if (_rule.api && value) { // 没填值没有校验的必要
          console.log(_rule.api, value);
          var params = detectKey(_rule.key, _rule, value);
          params.id = props.baseFromInfo.id || '';
          params.siteProtocol = formState.siteProtocol.value;
          let res = await request[`${_rule.api}`](params);
          if (!res) {
            return Promise.reject(`${_rule.msg2}`);
          } else {
            return Promise.resolve();
          }
        }
      }
    }
    return Promise.resolve()
  }
};

// TS
interface dataSourceType {
  [propName: string]: any;
}
// props 
const props = defineProps({
  baseFromInfo: {
    type: Object,
    default: {}
  },
  parentTitle: {
    type: [String, Number],
    default: ''
  },
  parentId: {
    type: [String, Number],
    default: ''
  },
})
//emit 
const emit = defineEmits(['checkSetTime']);
//data
// baseInfo - 从详情页传来
let baseInfo = reactive<dataSourceType>({ value: {} })
//站点协议 和 域名
const siteProtocol = reactive<dataSourceType>({
  siteProtocol: {
    value: 'https://',
    options: ['https://', 'http://'],
  }
})
const otherSiteProtocolsList = ref<dataSourceType[]>([]);
let uniqueCheck = reactive<dataSourceType>({});
const formState_old = { value: {} };// 无需响应式，记录baseInfo表单变化前的值;
const isIDUpdate = { value: false };
const formState = reactive<dataSourceType>({
  parent: {
    label: '上级站点',
    value: props.parentTitle
  },
  siteName: {
    value: "",
    rule: {
      required: true,
      validator: checkCreatSiteForm,
      trigger: ["blur"],
      msg1: '站点名称不可为空！',
      msg2: '列表或回收站中已存在相同的站点名称，请重新输入！',
      api: "fetchsiteManageTabledDataUniqueCheck",
      key: 'siteName',
      params: uniqueCheck,
      id: props.baseFromInfo.id,
    },
    placeholder: '请输入',
    label: "站点名称",
  },
  sitePath: {
    value: baseInfo.sitePath || '',
    rule: {
      required: true,
      validator: enNum,
      trigger: ["blur"],
      msg1: '站点目录不可为空！',
      msg2: '列表或回收站中已存在相同的站点目录，请重新选择！',
      api: "fetchsiteManageTabledDataUniqueCheck",
      key: 'sitePath',
      params: uniqueCheck,
      id: props.baseFromInfo.id,
    },
    placeholder: '仅支持输入数字、字母',
    label: "站点目录",
  },
  siteProtocol: {
    value: 'https://',
    options: ['https://', 'http://']
  },
  siteDomain: {
    value: "",
    rule: {
      required: true,
      validator: checkSiteDomainAlias,
      trigger: ["blur"],
      msg1: '站点域名不可为空！',
      msg2: '列表或回收站中已存在相同的域名，请重新输入！',
      api: "fetchsiteManageTabledDataUniqueCheck",
      key: 'siteDomain',
      params: uniqueCheck,
    },
    label: "站点域名",
  },
  siteDomainAlias: <dataSourceType[]>[],
  description: {
    value: "",
    label: "站点描述",
    placeholder: "不超过500个字",
  },
  status: {
    value: true,
    label: "站点状态",
  },
  oldStatus: 1,
  channelCopyOptions: {
    value: "",
    rule: {
      required: true,
      validator: checkCreatSiteForm,
      trigger: ["change"],
      msg1: '请选择栏目继承方式！',
      msg2: '',
      api: "",
      params: {}
    },
    label: "栏目继承",
  },
  seoTitle: {
    value: '',
    label: "SEO标题",
    placeholder: '请输入',
  },
  seoKeyword: {
    value: '',
    label: "SEO关键字",
    placeholder: '多个关键字用英文的逗号隔开',
  },
  seoDescription: {
    value: '',
    label: "SEO描述",
    placeholder: '请输入',
  },
});
const createSiteFrom = ref<any>(null); //整个form的ref，需要暴露到父组件
const ipt = ref<any>(null); // 主域名的input框ref
const sitePath_ref = ref<any>(null); // 站点路径的input框ref
// defineExpose //把子组件中的方法或变量暴漏给父组件
let formParams = reactive<dataSourceType>({});
//computed
formParams = computed(() => {
  return {
    "channelCopyOptions": formState.channelCopyOptions.value,
    "description": formState.description.value,
    "isOpen": formState.status.value,
    "status": formState.status.value,
    "parentId": props.parentId,
    "seoDescription": formState.seoDescription.value,
    "seoKeyword": formState.seoKeyword.value,
    "seoTitle": formState.seoTitle.value,
    "siteDomain": formState.siteDomain.value,
    "siteDomainAlias": (formState.siteDomainAlias.reduce((arr: [any], item: dataSourceType = {}, index: number) => {
      item.value && !arr.includes(item.value) && item.value != formState.siteDomain.value ? arr.push(item.value) : ''
      return arr
    }, [])).join(','),
    "siteName": formState.siteName.value,
    "sitePath": formState.sitePath.value,
    "siteProtocol": formState.siteProtocol.value
  }
});
uniqueCheck = computed(() => {
  return {
    siteDomain: formState.siteDomain.value,
    siteDomainAlias: '',
    siteName: formState.siteName.value,
    sitePath: formState.sitePath.value,
    siteProtocol: formState.siteProtocol.value,
    id: props.baseFromInfo.id,
  }
})
// watch
watch(() => props.baseFromInfo, (newVal: dataSourceType, oldVal) => {
  if (JSON.stringify(newVal) != JSON.stringify(oldVal)) {
    let keys = Object.keys(newVal);
    formState.siteDomainAlias = [];
    for (const i of keys) {
      if (formState.hasOwnProperty(i)) {
        if (i == 'siteDomainAlias' && newVal[i].length) {
          (newVal[i]).split(',').forEach((item: any) => {
            formState.siteDomainAlias.push({
              value: item,
              rule: {
                required: false,
                validator: checkSiteDomainAlias,
                trigger: ["blur"],
                msg1: '列表或回收站中已存在相同的域名，请重新输入!',
                msg2: '列表或回收站中已存在相同的域名，请重新输入！',
                api: "fetchsiteManageTabledDataUniqueCheck",
                key: 'siteDomainAlias',
                params: {},
                value: item,
              },
              placeholder: '请输入',
              label: "站点名称",
            });
          })
        }
        formState[i].value = newVal[i];
        if (i == 'siteName' || i == 'sitePath') {
          formState[i].rule.id = newVal.id;
        }
        if (i == 'status') {// 状态要特殊处理，status有0:手动关闭， 1:开启， 2:定时任务关闭
          formState[i].value = newVal[i] == 1 ? true : false;
          formState.oldStatus = newVal[i]; //用来记录最开始的关闭状态，因为false要对应0和2两个状态
        }
        formState[i].rule ? formState[i].rule.value = newVal[i] : '';
      }
    }
    baseInfo.value = newVal
    isIDUpdate.value = true;
  }

})
watch(() => cloneDeep(formState), (newVal, oldVal) => {
  if (!isIDUpdate.value) { //防止第一次进页面时拿到默认值
    formState_old.value = JSON.stringify(oldVal); //拿到已更新的旧值
  } else {
    formState_old.value = JSON.stringify(newVal);
  }
  nextTick(() => {
    isIDUpdate.value = false;
  })

}, { deep: true })
//methods
const selectChange = () => {
  ipt.value.focus();
  ipt.value.blur();
  let otherDomainIpts = document.querySelectorAll('.otherSiteProtocols input');
  otherDomainIpts.forEach((item: any) => {
    item.focus();
    item.blur();
  })
}
const valueChange = async (key: string, item: dataSourceType = {}) => {
  //formParams
  if (key) {
    formState[key].rule.params = uniqueCheck;
  } else if (item) {
    uniqueCheck.siteDomainAlias = item.value || ''
    item.rule.params = uniqueCheck;
  }
  if (key == 'siteName') {
    let params: dataSourceType = {
      text: formState.siteName.value,
    }
    if (formState.sitePath.value == '') {
      await request.fetchChiese2PY(params).then((res: dataSourceType) => {
        formState.sitePath.value = formState.sitePath.value || res;
      })

    }

  }
}
const changeSiteName = async () => {
  // let params: dataSourceType = {
  //   text: formState.siteName.value,
  // }
  // request.fetchChiese2PY(params).then((res: dataSourceType) => {
  //   formState.sitePath.value = formState.sitePath.value || res;
  // })
}
const addSiteDomain = () => {// 动态域名输入框表单并验证form表单
  formState.siteDomainAlias.push({
    value: "",
    rule: {
      required: false,
      validator: checkSiteDomainAlias,
      trigger: ["blur"],
      msg1: '填写',
      msg2: '列表或回收站中已存在相同的域名，请重新输入！',
      api: "fetchsiteManageTabledDataUniqueCheck",
      key: 'siteDomainAlias',
      params: {},
    },
    placeholder: '请输入',
    label: "站点名称",
  });
}
const checkSetTime = () => {
  emit('checkSetTime', true)
}
const deleteOtherSPList = (index: number) => {
  formState.siteDomainAlias.splice(index, 1);
}
const closeSite = () => {
  formState.status.value = false;
  formState.oldStatus = 0;

}

//暴漏组件方法
defineExpose({ createSiteFrom, formParams, formState, formState_old });
</script>

<style lang="less" scoped>
.otherSiteProtocols {
  margin-top: 16px;
}

.addSiteDomain {
  height: 14px;
  font-size: 14px;
  font-weight: 400;
  color: var(--theme_text_hightlight_color, #2f54eb);
  line-height: 14px;
  margin-top: 8px;
  margin-bottom: 18px;
  width: 100%;
  text-align: right;
  cursor: pointer;
}

.addSiteDomain:hover {
  color: var(--theme_button_hover_bg_color, #597ef7);
}

.addSiteDomain:active {
  color: var(--theme_button_active_bg_color, #1d39c4);
}

.addSiteDomain_maringTop {
  margin-top: -16px;
  margin-bottom: 18px;
}

.otherFormItems {
  padding-left: 83px;
  margin-bottom: 0px;
}

.delete-iconfont {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
  line-height: 32px;
  margin-left: 12px;
}

.delete-iconfont:hover {
  color: rgba(0, 0, 0, 0.85)
}

.siteDomain {
  margin-bottom: 0px;
}

.description,
.status {
  margin-bottom: 12px;

}

.setTime {
  font-size: 14px;
  font-weight: 400;
  color: #1F6DED;
  margin-left: 24px;
  cursor: pointer;
}

.channelCopyOptions {
  margin-bottom: 0px
}

:deep(.ant-form-item) {
  width: 592px;
  display: flex;

  .ant-form-item-control {
    width: 505px;
    margin-left: 4px;
    flex: unset;
  }

  .ant-form-item-label {
    flex-grow: 0;
    width: 83px;
    text-align: right;
  }
}

::v-deep(.ant-form) {
  line-height: 1;
}

::v-deep(.siteDomain-input) {
  width: 399px;
}

::v-deep(.siteDomainAlias-input) {
  width: 371px;
}

::v-deep(.ant-form-item:nth-of-type(1)) {
  margin-left: 0px;
  margin-top: -8px;
  margin-bottom: 24px;
}

::v-deep(.ant-form-item:nth-last-of-type(1)) {
  margin-left: 0px;
  margin-bottom: 10px;
}

::v-deep(.ant-input-affix-wrapper:hover) {
  .anticon-close-circle {
    display: block;
  }

  .ant-input-show-count-suffix {
    // display: none;
  }
}

::v-deep(.ant-input-affix-wrapper:focus) {
  .anticon-close-circle {
    display: none;
  }

  .ant-input-show-count-suffix {
    display: block;
  }
}



::v-deep(.ant-input-affix-wrapper-textarea-with-clear-btn) {
  min-height: 80px;
  position: relative;
}

::v-deep(.ant-input-textarea-show-count) {
  position: relative;
}

::v-deep(.ant-input-textarea-show-count::after) {
  position: absolute;
  right: 12px;
  bottom: 26px;
  line-height: 1;
}

::v-deep(.ant-radio-group) {
  margin-top: 5px;
}

::v-deep(.ant-radio-wrapper:nth-child(1)) {
  margin-bottom: 12px;
}

::v-deep(.SEOSetting) {
  font-size: 14px;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.85);
  line-height: 22px;
  position: relative;
  margin-bottom: 16px;
  margin-top: 14px;
}

::v-deep(.SEOSetting::after) {
  width: 3px;
  height: 12px;
  background: #1F6DED;
  border-radius: 0px 0px 0px 0px;
  opacity: 1;
  content: '';
  position: absolute;
  left: -8px;
  z-index: 1;
  top: 4px;
}
</style>